/**
 * ...
 * @author Krzysztof Rozalski
 */

package hapi.sprite.display;
import flash.display.DisplayObjectContainer;
import flash.display.Sprite;
import flash.geom.Point;
import hapi.sprite.sheet.BitmapFillSpriteSheet;

class InteractiveSpriteSheetDisplay extends Sprite, implements SpriteSheetDisplay, implements Displayable {

	var spriteSheet:BitmapFillSpriteSheet;
	var dest:Point;
	public var currentFrame(default, null):Int;
	public var totalFrames(default, null):Int;
	
	public function new(spriteSheet:BitmapFillSpriteSheet, ?x:Float=0.0, ?y:Float=0.0) {
		super();
		this.spriteSheet = spriteSheet;
		this.dest = new Point(0.0, 0.0);
		this.totalFrames = spriteSheet.totalFrames;
		this.currentFrame = 1;
		this.moveTo(x, y);
	}
	
	public inline function isVisible():Bool {
		return visible;
	}
	
	public function show():Void {
		this.visible = true;
	}
	
	public function hide():Void {
		this.visible = false;
	}
	
	public function goto(frame:Int) {
		if(frame <= totalFrames && frame >= 1 && this.currentFrame != frame) {
			this.currentFrame = frame;
			render();
		}
	}
	
	inline function render() {
		if(isVisible()) {
			graphics.clear();
			spriteSheet.drawSpriteOn(graphics, currentFrame, dest);
		}
	}
	
	public inline function moveTo(x:Float, y:Float):Void {
		this.x = x;
		this.y = y;
	}
	
	public function addToDisplayList(root:DisplayObjectContainer, ?x:Null<Float>, ?y:Null<Float>):Void {
		root.addChild(this);
		if (x == null ) x = this.x;
		if (y == null ) y = this.y;
		moveTo(x, y);
	}
}